package com.example.apidocserver.application.event.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.example.apidocserver.application.event.YuqueEvent;
import com.example.apidocserver.infrastructure.config.input.YuqueYmlConfig;
import com.example.apidocserver.infrastructure.constants.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class YuqueEventImpl implements YuqueEvent {
    private final RestTemplate restTemplate = new RestTemplate();

    private JSONObject body;

    private HttpEntity<Object> requestEntity;

    public YuqueEventImpl() {
        setBody();
        setRequest();
    }

    private void setBody() {
        body = new JSONObject();
        body.put("slug", YuqueYmlConfig.SLUG);
        body.put("title", YuqueYmlConfig.TITLE);
        body.put("public", "0");
        body.put("format", "lake");
    }

    private void setRequest() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.add("X-Auth-Token", YuqueYmlConfig.TOKEN);
        this.requestEntity = new HttpEntity<>(this.body, httpHeaders);
    }

    @Override
    public void send(String str) {
        if (SystemConstants.TRUE.equals(YuqueYmlConfig.SWITCH_CONFIG)) {
            body.put("body", str);
            long start = System.currentTimeMillis();
            restTemplate.exchange(YuqueYmlConfig.URL, HttpMethod.PUT, this.requestEntity, String.class);
            log.info("语雀请求时间：{}ms", System.currentTimeMillis() - start);
        } else {
            log.info("语雀请求已关闭。");
        }
    }
}
